# -*- coding: utf-8 -*-

"""
调试评论页面的元素定位
"""

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
import time
import re

def test_review_page():
    """
    测试评论页面元素定位
    """
    print("开始测试评论页面元素定位...")
    
    try:
        # 配置Chrome选项
        chrome_options = Options()
        chrome_options.add_argument("--headless")  # 无头模式
        chrome_options.add_argument("--no-sandbox")
        chrome_options.add_argument("--disable-dev-shm-usage")
        chrome_options.add_argument("--disable-gpu")
        chrome_options.add_argument("--window-size=1920,1080")
        chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
        
        # 指定chromedriver路径
        service = Service("/usr/bin/chromedriver")
        
        # 创建WebDriver实例
        print("正在初始化WebDriver...")
        driver = webdriver.Chrome(service=service, options=chrome_options)
        
        # 访问一个商品的评论页面进行测试
        test_url = "https://www.amazon.com/product-reviews/B0DR9PNXX3"
        print(f"正在访问评论页面: {test_url}")
        driver.get(test_url)
        time.sleep(5)  # 等待页面加载
        
        # 检查页面标题
        print(f"页面标题: {driver.title}")
        
        # 尝试定位评论元素
        print("\n=== 评论元素测试 ===")
        review_selectors = [
            ".review",
            "[data-hook='review']",
            ".a-section.review.aok-relative",
        ]
        
        for selector in review_selectors:
            try:
                elements = driver.find_elements(By.CSS_SELECTOR, selector)
                print(f"选择器 '{selector}': 找到 {len(elements)} 个元素")
            except Exception as e:
                print(f"选择器 '{selector}' 出错: {e}")
        
        # 获取第一个评论元素进行详细分析
        try:
            review_elements = driver.find_elements(By.CSS_SELECTOR, ".review")
            if review_elements:
                print(f"\n找到 {len(review_elements)} 个评论元素")
                first_review = review_elements[0]
                print("分析第一个评论元素...")
                
                # 评论ID
                review_id = first_review.get_attribute("id")
                print(f"评论ID: {review_id}")
                if review_id:
                    id_match = re.search(r'customer_review-([A-Z\d]+)', review_id)
                    if id_match:
                        print(f"提取评论ID: {id_match.group(1)}")
                
                # 评论标题
                try:
                    title_element = first_review.find_element(By.CSS_SELECTOR, ".review-title span")
                    title_text = title_element.text
                    print(f"评论标题: {title_text}")
                except Exception as e:
                    print(f"获取评论标题出错: {e}")
                
                # 评论内容
                try:
                    content_elements = first_review.find_elements(By.CSS_SELECTOR, ".review-text-content span")
                    if not content_elements:
                        content_elements = first_review.find_elements(By.CSS_SELECTOR, ".review-text span")
                    
                    content_text = ' '.join([elem.text for elem in content_elements]).strip()
                    print(f"评论内容: {content_text[:100]}...")
                except Exception as e:
                    print(f"获取评论内容出错: {e}")
                
                # 评分
                try:
                    rating_element = first_review.find_element(By.CSS_SELECTOR, ".review-rating span")
                    rating_text = rating_element.text
                    print(f"评分文本: {rating_text}")
                    rating_match = re.search(r'(\d+\.?\d*) out of 5', rating_text)
                    if rating_match:
                        print(f"提取评分: {rating_match.group(1)}")
                except Exception as e:
                    print(f"获取评分出错: {e}")
                
                # 用户名
                try:
                    user_element = first_review.find_element(By.CSS_SELECTOR, ".a-profile-name")
                    user_text = user_element.text
                    print(f"用户名: {user_text}")
                except Exception as e:
                    print(f"获取用户名出错: {e}")
                
                # 日期
                try:
                    date_element = first_review.find_element(By.CSS_SELECTOR, ".review-date")
                    date_text = date_element.text
                    print(f"日期: {date_text}")
                except Exception as e:
                    print(f"获取日期出错: {e}")
                
                # 点赞数
                try:
                    helpful_element = first_review.find_element(By.CSS_SELECTOR, ".cr-helpful-vote-text")
                    helpful_text = helpful_element.text
                    print(f"点赞数文本: {helpful_text}")
                    if helpful_text:
                        helpful_count = re.sub(r'[^\d]', '', helpful_text)
                        if helpful_count:
                            print(f"提取点赞数: {helpful_count}")
                except Exception as e:
                    print(f"获取点赞数出错: {e}")
                
            else:
                print("未找到评论元素")
        except Exception as e:
            print(f"分析评论元素出错: {e}")
        
        # 检查是否有下一页
        print("\n=== 分页元素测试 ===")
        pagination_selectors = [
            "ul.a-pagination li.a-last a",
            ".a-pagination .a-last a",
            "[data-hook='pagination-bar']",
        ]
        
        for selector in pagination_selectors:
            try:
                elements = driver.find_elements(By.CSS_SELECTOR, selector)
                print(f"选择器 '{selector}': 找到 {len(elements)} 个元素")
                for i, element in enumerate(elements):
                    text = element.text.strip()
                    attr_value = element.get_attribute("href")
                    print(f"  元素 {i+1}: 文本='{text}', href='{attr_value}'")
            except Exception as e:
                print(f"选择器 '{selector}' 出错: {e}")
        
        # 关闭浏览器
        driver.quit()
        print("\n测试完成!")
        
    except Exception as e:
        print(f"测试过程中出现错误: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    test_review_page()